<template>

    <div class="register-div-center">
        <img src="@/assets/img/favicon.png" alt="logo">
    </div>
    <el-form label-position="right" label-width="auto" size="large" :model="registerParam" :disabled="disabled"
        class="register-form">
        <el-form-item label="账号：" label-position="">
            <el-input v-model="registerParam.account" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="姓名：" label-position="">
            <el-input v-model="registerParam.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="密码：" label-position="">
            <el-input v-model="registerParam.password" show-password type="password" placeholder="请输入5～16位非空字符"/>
        </el-form-item>
    </el-form>
    <div class="register-div-center">
        <el-button size="large" color="#5CAF90" plain class="register-from-bu" :loading="buLoading"
            @click="toRegisterClick">
            注册
        </el-button>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { HttpMethod } from '@/api/types';
import { ElMessage } from 'element-plus';
import { apiRequest } from '@/api/apiService';


const router = useRouter();         // 路由实例
const disabled = ref(false);        // 按钮不可用
const buLoading = ref(false);       // 按钮loading
const registerParam = reactive({    // 注册参数
    account: '',
    name: '',
    password: ''
})

// 点击注册
const toRegisterClick = () => {
    buLoading.value = true;
    disabled.value = true;
    if (registerParam.account.length === 0 || registerParam.name.length === 0 || registerParam.password.length === 0) {
        ElMessage({
            message: '表单项存在空值，请补全！',
            type: 'error',
        });
        buLoading.value = false;
        disabled.value = false;
    } else {
        toRegister();
    }
}

// 发送请求
const toRegister = async () => {
    try {
        const url = '/auth/register';
        await apiRequest.request<any>(HttpMethod.POST, url, registerParam);
        buLoading.value = false;
        disabled.value = false;
        router.push({ name: '/', });
    } catch (error) {
        console.log('request: /api/auth/register failed, error message: ', error);
        buLoading.value = false;
        disabled.value = false;
    }
};
</script>

<style scoped>
.register-div-center {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;

}

.register-form {
    margin: 20px auto;
    width: 400px;
}

.register-from-bu {
    width: 150px;
}
</style>